package com.example.clientaidl;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;

import com.example.server_aidl.IRemoteService;
import com.example.server_aidl.Rect;

public class MainActivity extends AppCompatActivity {
    private final String TAG = "MainActivity";
    private IRemoteService iRemoteService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    //绑定服务
    @Override
    protected void onStart() {
        super.onStart();
        Intent intent = new Intent();
        //对应注册服务的action
        intent.setAction("com.example.aidl");
        //对应服务端包名
        intent.setPackage("com.example.serveraidl");
        bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
    }

    //解绑
    @Override
    protected void onStop() {
        super.onStop();
        unbindService(mConnection);
    }

    ServiceConnection mConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            Log.d(TAG, "onServiceConnected");
            //asInterface
            //该方法会接收 IBinder（通常是传递给客户端 onServiceConnected() 回调方法的参数），并返回 Stub 接口的实例。
            iRemoteService = IRemoteService.Stub.asInterface(iBinder);
            try {
                iRemoteService.basicTypes(0, 1, true, 2, 3, "文本");
                iRemoteService.addRectInOut(new Rect(1, 2, 3, 4));
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            Log.d(TAG, "onServiceDisconnected");
            iRemoteService = null;
        }
    };
}